from django.shortcuts import render, redirect

from app01 import models
from app01.utils.pagination import Pagination


def admin_list(request):
    """管理员列表"""
    """
    已有中间件代替
        # 检测用户是否已登录，已登录，继续往下走，未登录的话跳转回登录页面
        # 获取用户发来得到请求，获取到cookie的随机字符串，拿到随机字符串看看在session中有没有
        # request.session['info']     # 有就获取，没有则报错
        # info = request.session.get('info')
        # # {'id': 10, 'name': 'wupingzs'} 已登录\\  None 未登录
        # # print(info)
        # if not info:    # 没有值
        #     return redirect('/login/')
    """

    # 显示登录信息
    info_dict = request.session['info']
    # print(info_dict)
    # print(info_dict['id'])
    # print(info_dict['name'])



    # 搜索
    # 构造搜索条件
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['username__contains'] = search_data

    # 根据搜索条件去数据库获取
    queryset = models.Admin.objects.filter(**data_dict)
    # 分页
    page_object = Pagination(request, queryset)
    context = {
        "search_data": search_data,

        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }

    return render(request, 'admin_list.html', context)


from django import forms
from django.core.exceptions import ValidationError  # 抛出异常
from app01.utils.bootstrap import BootStrapModelFrom
from app01.utils.encrypt import md5


class AdminModelForm(BootStrapModelFrom):
    # 数据库中没有确认密码，在这自己定义一个字段
    confirm_passeord = forms.CharField(
        label="确认密码",
        # render_value=True 下面判断错误了输入框不清空
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ['username', 'password', 'confirm_passeord']
        # 已以字段设置样式
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        # 拿到密码
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    # 钩子函数【判断密码和确认密码是否一致
    def clean_confirm_passeord(self):
        print(self.cleaned_data)
        pwd = self.cleaned_data.get('password')  # 输入的密码
        confirm = md5(self.cleaned_data.get('confirm_passeord'))  # 确认输入的密码

        if confirm != pwd:
            raise ValidationError('密码不一致，请重新输入')
        # 下面save保存到数据库时 会保存的是cleaned_data里面的confirm
        return confirm


class AdminEditModelForm(BootStrapModelFrom):
    class Meta:
        model = models.Admin
        fields = ['username']


class AdminResetModelForm(BootStrapModelFrom):
    # 数据库中没有确认密码，在这自己定义一个字段
    confirm_password = forms.CharField(
        label="确认密码",
        # render_value=True 下面判断错误了输入框不清空
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widget = forms.PasswordInput(render_value=True)

    def clean_password(self):
        # 拿到密码
        pwd = self.cleaned_data.get('password')
        # 想要重置的秘密和以前的秘密不能一致，那就要到数据库中校验下
        md5_pwd = md5(pwd)
        # 去数据库中校验 当前的秘密和新输入的秘密是否一致
        exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        if exists:
            raise ValidationError('密码不能于之前的一致')
        return md5_pwd

    # 钩子函数【判断密码和确认密码是否一致
    def clean_confirm_password(self):
        print(self.cleaned_data)
        pwd = self.cleaned_data.get('password')  # 输入的密码
        confirm = md5(self.cleaned_data.get('confirm_password'))  # 确认输入的密码

        if confirm != pwd:
            raise ValidationError('密码不一致，请重新输入')
        # 下面save保存到数据库时 会保存的是cleaned_data里面的confirm
        return confirm


def admin_add(request):
    """添加管理账户 """
    title = "添加管理"
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, 'change_add.html', {
            "form": form,
            "title": title,
        })

    # 接收用户post传来的值
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        # cleaned_data  验通过后的所有数据
        # if form.cleaned_data['password'] == form.cleaned_data['confirm_passeord']:
        form.save()
        return redirect('/admin/list/')

    return render(request, 'change_add.html', {
        "form": form,
        "title": title,
    })


def admin_edit(request, nid):
    """编辑管理员"""

    # 先判断nid那个id是否存在【获取当前对象/Mome
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return render(request, 'error.html', {"msg": "数据不存在 "})

    title = '编辑管理员'

    if request.method == 'GET':
        # 页面和新增一样的话可以直接使用新增的modelform
        # form = AdminModelForm()

        # 只允许编辑用户名
        # instance=row_object 显示默认值
        form = AdminEditModelForm(instance=row_object)
        return render(request, 'change_add.html', {
            "form": form,
            "title": title,
        })
    # post
    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    # 否则就抱错误信息
    return render(request, 'change_add.html', {
        "form": form,
        "title": title,
    })


def admin_delete(request, nid):
    """删除管理员"""
    models.Admin.objects.filter(id=nid).delete()
    return redirect("/admin/list/")


def admin_reset(request, nid):
    """重置密码"""
    # 先判断nid那个id是否存在【获取当前对象/Mome
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('admin/list/')
    title = '重置密码---{}'.format(row_object.username)
    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request, 'change_add.html', {
            "form": form,
            "title": title,
        })

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')

    return render(request, 'change_add.html', {
        "form": form,
        "title": title,
    })
